package echat.future.cn.echat.my.view;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;

import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import echat.future.cn.echat.R;
import echat.future.cn.echat.databinding.ActivityArtPhotoBinding;
import echat.future.cn.echat.my.adapter.ArtSelecotrAdapter;
import echat.future.cn.echat.my.api.UserApi;
import echat.future.cn.echat.my.bean.ImageBean;
import echat.future.cn.echat.my.bean.VideoBean;
import echat.future.cn.echat.my.utils.HttpUtilsRequst;
import echat.future.cn.echat.my.utils.UserHelper;
import echat.future.cn.echat.my.weight.Navagation.AdapterNavagation;
import echat.future.cn.echat.my.weight.Navagation.IBaseNavagation;
import echat.future.cn.echat.my.weight.dialog.ChoosePicDialog;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * 我的艺术照
 */
public class ArtPhotoActivity extends BaseActivity <ActivityArtPhotoBinding>{

    Dialog choosePicDialog;
    /**
     * 艺术照适配器
     */
    private ArtSelecotrAdapter artSelecotrAdapter;

    private List<ImageBean> imageBeans = new ArrayList<>();

    @Override
    public int layoutId() {
        return R.layout.activity_art_photo;
    }

    @Override
    public IBaseNavagation navagation() {
        return new AdapterNavagation(this).setTitle("我的艺术照",16,R.color.white).
                setBack(R.drawable.btn_back).
                setNavagationBackgroudColor(R.color.color_161823);
    }

    @Override
    public void initView() {
        imageBeans.add(new ImageBean());
        artSelecotrAdapter = new ArtSelecotrAdapter(this.imageBeans);
        bind.recyclerView.setLayoutManager(new GridLayoutManager(this,3));
        artSelecotrAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            if(view.getId() == R.id.add){
                showChooseDialog();
            }
            if(view.getId() == R.id.delete){
                deleteViedio(imageBeans.get(position).getId());
            }
        });
        bind.recyclerView.setAdapter(artSelecotrAdapter);
        getArtPhoto();
    }

    private void showChooseDialog(){
        if(choosePicDialog == null){
            choosePicDialog = new ChoosePicDialog.Builder(this)
                    .content("选择艺术照来源")
                    .photoListenter(v -> choosePic())
                    .cameroListenter(v ->chooseCamero()).Builder();
        }
        choosePicDialog.show();
    }



    private void choosePic() {
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .maxSelectNum(1)
                .enableCrop(true)
                .withAspectRatio(1,1)
                .isCamera(false)
                .forResult(PictureConfig.CHOOSE_REQUEST);
        if(choosePicDialog!=null)
            choosePicDialog.dismiss();
    }


    private void chooseCamero() {
        PictureSelector.create(this).openCamera(PictureMimeType.ofImage())
                .maxSelectNum(1)
                .enableCrop(true)
                .withAspectRatio(1,1)
                .isCamera(true)
                .forResult(PictureConfig.CHOOSE_REQUEST);
        if(choosePicDialog!=null)
            choosePicDialog.dismiss();
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data){
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == PictureConfig.CHOOSE_REQUEST) {
                // 图片选择结果回调
                List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                // 例如 LocalMedia 里面返回三种path
                // 1.media.getPath(); 为原图path
                // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                for(int i=0;i<selectList.size();i++) {
                    LocalMedia media = selectList.get(i);
                    String headImgPath = "";
                    if (media.isCut()) {
                        headImgPath = media.getCutPath();
                    } else {
                        headImgPath = media.getPath();
                    }
                    addPic(headImgPath);
                }
            }
        }
    }


    private void getArtPhoto(){
        new HttpUtilsRequst<List<VideoBean>>(this,
                HttpUtilsRequst.retrofitClient.create(UserApi.class).getMyPic(UserHelper.getToken()))
                .setmOnRequstSuccessListener((HttpUtilsRequst.OnRequstSuccessListener<List<VideoBean>>) o -> {
                    imageBeans.clear();
                    imageBeans.add(new ImageBean());
                    for (VideoBean v:o){
                        imageBeans.add(viedio2ImageBean(v));
                    }
                    artSelecotrAdapter.notifyDataSetChanged();
                })
                .start();
    }

    private ImageBean viedio2ImageBean(VideoBean videoBean){
        ImageBean imageBean = new ImageBean();
        imageBean.setImg(videoBean.getImg());
        imageBean.setId(videoBean.getId());
        return imageBean;
    }


    private void addPic(String pic){
        RequestBody requestBody = RequestBody.create(MediaType.parse("image/jpeg"), new File(pic));
        MultipartBody.Part  partViedoy = MultipartBody.Part.createFormData("img[0]", new File(pic).getName(), requestBody);
        new HttpUtilsRequst<String>(this,HttpUtilsRequst.retrofitClient.create(UserApi.class).uploadMyPic(UserHelper.getToken(),partViedoy))
                .setmOnRequstSuccessListener(new HttpUtilsRequst.OnRequstSuccessListener() {
                    @Override
                    public void onSuccss(Object o) {
                        toast("上传成功");
                        getArtPhoto();
                    }
                })
                .start();
    }


    public void deleteViedio(int id){
        new HttpUtilsRequst<String>(this,HttpUtilsRequst.retrofitClient.create(UserApi.class).deletePic(
                UserHelper.getToken(),
                id
        )).setmOnRequstSuccessListener((HttpUtilsRequst.OnRequstSuccessListener<String>) o -> {
            toast("删除艺术照成功");
            getArtPhoto();
        })
                .start();
    }
}
